package service

import (
	"perfect-admin/dao"
	"perfect-admin/model"
	"perfect-admin/model/request"
	"strconv"
)

func GetRoleList() (roles []model.SysRole, err error) {
	err = dao.DB.Find(&roles).Error
	return
}

func GetAllRoleMenuTree(queryInfo request.QueryInfo) (roles []*model.SysRole, total int, err error) {
	if queryInfo == (request.QueryInfo{}){
		if err = dao.DB.Model(&model.SysRole{}).Count(&total).Error; err != nil{
			return
		}
		err = dao.DB.Preload("SysBaseMenus").Find(&roles).Error
	}else if queryInfo.Query == "" {
		if err = dao.DB.Model(&model.SysRole{}).Count(&total).Error; err != nil{
			return
		}
		err = dao.DB.Limit(queryInfo.PageSize).Offset((queryInfo.PageNum-1) * queryInfo.PageSize).Preload("SysBaseMenus").Find(&roles).Error
	}else{
		if err = dao.DB.Model(&model.SysRole{}).Where("role_name like ?", "%" + queryInfo.Query + "%").Count(&total).Error; err != nil{
			return
		}
		err = dao.DB.Where("role_name like ?", "%" + queryInfo.Query + "%").Limit(queryInfo.PageSize).Offset((queryInfo.PageNum-1)*queryInfo.PageSize).Preload("SysBaseMenus").Find(&roles).Error
	}
	if err != nil {
		return
	}
	for _, role := range roles{
		menus, _, _ := GetMenuTree(role.SysBaseMenus)
		role.Children = menus
	}
	return
}

func AddOneRole(role model.SysRole) error {
	return dao.DB.Create(&role).Error
}

func UpdateRole(role model.SysRole) error {
	return dao.DB.Model(&model.SysRole{}).Where(&model.SysRole{RoleId:role.RoleId}).Updates(&model.SysRole{RoleName:role.RoleName, RoleDesc:role.RoleDesc}).Error
}

func DeleteRole(role_id int) error {
	return dao.DB.Delete(&model.SysRole{RoleId:role_id}).Error
}

func UpdateRoleMenus(menu_id_list []string, role_id int) (err error) {
	var menus []model.SysBaseMenu
	err = dao.DB.Where("id in (?)", menu_id_list).Find(&menus).Error
	if err != nil || len(menus) == 0 {
		return
	}
	return dao.DB.Model(&model.SysRole{RoleId:role_id}).Association("SysBaseMenus").Replace(menus).Error
}

func DeleteRoleRight(role_id int, menu_ids []string) (err error) {
	for _, id := range menu_ids {
		menu_id, _ := strconv.Atoi(id)
		delete_sql := "delete FROM `sys_role_menus` where sys_role_role_id=? and sys_base_menu_id=?"
		err = dao.DB.Exec(delete_sql, role_id, menu_id).Error
	}
	return
}